import React from "react";
import videoItemAPI from '@/api/model/video-item';
import videoAPI from '@/api/model/video';
import {Button, Descriptions, Empty, Form, Modal, Popconfirm, Table, Tag, Toast, Tooltip} from "@douyinfe/semi-ui";
import styles from './index.less'
import {IconCopyAdd} from "@douyinfe/semi-icons";
import Column from "@douyinfe/semi-ui/lib/es/table/Column";
import {IllustrationNoContent, IllustrationNoContentDark} from "@douyinfe/semi-illustrations";

class VideoItem extends React.Component {
    private formApi: any;

    constructor(props: any) {
        super(props);
        this.state = {
            videoDetail: {},
            // @ts-ignore
            tableLoading: false,
            isCreate: true,
            visible: false,
            saveLoading: false,
            pagination: {
                page_size: 10,
                page_current: 1,
                total: 0,
            },
            data: [],
            formData: {},
        }

        this.showDialog = this.showDialog.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.updatebooktype = this.updatebooktype.bind(this);
        this.handlePageChange = this.handlePageChange.bind(this);
        this.getVideoDetail = this.getVideoDetail.bind(this);
    }

    componentDidMount() {
        this.getVideoDetail();
        this.getVideoItem()
    }

    showDialog() {
        this.setState({
            visible: true,
            isCreate: true,
        });
    }

    handleCancel() {
        this.setState({
            visible: false,
        });
    }

    async updatebooktype() {
        await this.setState({
            visible: true,
            isCreate: false,
        });
        const {formData}: any = this.state
        await this.formApi.setValue('videoNumber', formData.videoNumber);
        await this.formApi.setValue('videoUrl', formData.videoUrl);
        await this.formApi.setValue('id', formData.id);

    }

    // 获取分类列表
    async getVideoItem() {
        this.setState({
            tableLoading: true,
        });
        const id: any = window.sessionStorage.getItem('videoId')
        const res = await videoItemAPI.videoItemList({id});
        this.setState({
            data: res.data,
        });
    }

    async handleSubmit(e: any) {
        const {isCreate, videoDetail}: any = this.state;
        this.setState({
            saveLoading: true,
        });
        let res: any = {};
        if (isCreate) {
            res = await videoItemAPI.addVideoItem({...e, videoId: videoDetail.id});
        } else {
            res = await videoItemAPI.editVideoItem({...e, videoId: videoDetail.id});
        }

        if (res.status) {
            Toast.success({
                content: `${isCreate ? '创建' : '修改'}书签分类成功！`,
                duration: 3,
            });
            setTimeout(async () => {
                await this.getVideoItem();
                this.setState({
                    visible: false,
                    saveLoading: false,
                });
            }, 350);
        } else {
            this.setState({
                visible: false,
                saveLoading: false,
            });
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    async handlePageChange(page_current: number) {
        const {pagination}: any = this.state;
        await this.setState({
            pagination: {
                ...pagination,
                page_current,
            },
        });
        await this.getVideoItem();
    }

    async delBookType() {
        const {formData}: any = this.state;
        const res = await videoItemAPI.deleteVideoItem({id: formData.id});
        if (res.status) {
            Toast.success({
                content: `删除成功！`,
                duration: 3,
            });
            await this.getVideoItem();
        } else {
            Toast.error({
                content: res.data.error,
                duration: 3,
            });
        }
    }

    getFormApi(formApi: any) {
        this.formApi = formApi;
    }

    async getVideoDetail() {
        const id: any = window.sessionStorage.getItem('videoId')
        const res = await videoAPI.getVideoDetail({id})
        console.log('res', res)
        this.setState({
            videoDetail: res.data
        })
    }

    render() {
        const emptyStyle = {
            padding: 30,
        };
        const {
            data,
            visible,
            formData,
            isCreate,
            saveLoading,
            videoDetail,
            pagination,
            tableLoading,
            modalVisible,
        }: any = this.state;
        return (
            <div className={styles.video_item_container}>
                <VideoDetail videoDetail={videoDetail}/>
                <div className={styles.video_item_content}>
                    <div className={styles.header}>
                        <Button onClick={this.showDialog} icon={<IconCopyAdd/>} theme="solid"
                                style={{marginRight: 10}}>添加子集</Button>
                    </div>

                    <div className={styles.video_item_list}>
                        <Table dataSource={data} pagination={false}
                               empty={
                                   <Empty
                                       image={
                                           <IllustrationNoContent style={{width: 150, height: 150}}/>
                                       }
                                       darkModeImage={
                                           <IllustrationNoContentDark
                                               style={{width: 150, height: 150}}
                                           />
                                       }
                                       description={'暂无内容，请添加'}
                                       style={emptyStyle}
                                   />
                               }
                               onRow={(record, index) => {
                                   return {
                                       onClick: (event) => {
                                           this.setState({
                                               formData: record,
                                           });
                                       },
                                   };
                               }}>
                            <Column title="视频ID" dataIndex="videoId" key="videoId"/>
                            <Column title="视频第几集" dataIndex="videoNumber" key="videoNumber"/>
                            <Column title="视频URL" dataIndex="videoUrl" key="videoUrl"/>
                            <Column
                                title=""
                                render={() => {
                                    return (
                                        <>
                                            <Tooltip content={'修改书签分类'}>
                                                <Button
                                                    onClick={this.updatebooktype}
                                                    theme="light"
                                                    type="secondary"
                                                    style={{marginRight: 8}}
                                                >
                                                    修改
                                                </Button>
                                            </Tooltip>
                                            <Popconfirm
                                                content="是否确认删除"
                                                onConfirm={() => this.delBookType()}
                                            >
                                        <span style={{display: 'inline-block'}}>
                                          <Tooltip content={'删除书签分类'}>
                                            <Button
                                                theme="light"
                                                type="danger"
                                                style={{marginRight: 8}}
                                            >
                                              删除
                                            </Button>
                                          </Tooltip>
                                        </span>
                                            </Popconfirm>
                                        </>
                                    );
                                }}
                            />
                        </Table>
                    </div>
                </div>
                <ModalForm
                    showDialog={this.showDialog}
                    getFormApi={(e: any) => this.getFormApi(e)}
                    saveLoading={saveLoading}
                    formData={formData}
                    isCreate={isCreate}
                    visible={visible}
                    handleCancel={this.handleCancel}
                    handleSubmit={(e: any) => this.handleSubmit(e)}
                />
            </div>
        )
    }
}

export default VideoItem

const VideoDetail = ({videoDetail}: any) => {
    const {videoName, cover, shortDescribe, describe, isMovies, bluesNumber} = videoDetail
    const data = [
        {key: '视频名称', value: videoName},
        {key: '视频封面', value: cover},
        {key: '视频总集', value: <Tag color='orange' style={{margin: 0}}>{bluesNumber}</Tag>},
        {key: '视频简短描述', value: shortDescribe},
        {key: '视频描述', value: describe},
        {key: '是都是电影', value: <Tag color='blue' type='solid' style={{margin: 0}}>{isMovies ? '是' : '不是'}</Tag>},
    ];
    const style = {
        boxShadow: 'var(--semi-shadow-elevated)',
        backgroundColor: 'var(--semi-color-bg-2)',
        borderRadius: '10px',
        padding: '10px',
        margin: '10px',
        width: '600px',
    };
    return (
        <>
            <div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'center', marginTop: '20px'}}>
                <Descriptions align="center" data={data} style={style}/>
            </div>
        </>
    );
};


const ModalForm = (props: any) => {
    return (
        <>
            <Modal
                title={props.isCreate ? '新建' : '编辑'}
                visible={props.visible}
                onCancel={props.handleCancel}
                className="modalStyle"
                centered
                footer={''}
            >
                <div style={{paddingBottom: '1rem'}}>
                    <Form
                        getFormApi={props.getFormApi}
                        onSubmit={(values) => props.handleSubmit(values)}
                        style={{width: 400}}
                    >
                        {({formState, values, formApi}) => (
                            <>
                                <Form.Input
                                    rules={[{required: true, message: '请输入视频链接'}]}
                                    field="videoUrl"
                                    label="视频链接"
                                    style={{width: '100%'}}
                                    placeholder="请输入视频链接"
                                />
                                <Form.Input
                                    rules={[{required: true, message: '请输入视频集'}]}
                                    field="videoNumber"
                                    label="视频集"
                                    style={{width: '100%'}}
                                    placeholder="请输入视频集"
                                />
                                <div style={{display: 'flex', justifyContent: 'flex-end'}}>
                                    <Button
                                        htmlType="submit"
                                        type="tertiary"
                                        loading={props.saveLoading}
                                    >
                                        提 交
                                    </Button>
                                </div>
                            </>
                        )}
                    </Form>
                </div>
            </Modal>
        </>
    );
};
